package com.cooper.controllers.seller;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.cooper.controllers.Controller;
import com.cooper.controllers.LoginRequired;
import com.cooper.core.JsonResult;
import com.cooper.entity.DesignerEntity;
import com.cooper.entity.UserInfo;
import com.cooper.service.seller.DesignerService;
import com.cooper.util.Controllers;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.portal.Portal;

@LoginRequired
public class PersonLifeController extends Controller {

	@Autowired
	private DesignerService designerService;
	
	@Get("edit")
	public String execute(Invocation inv,Portal portal) {
		Long sellerId = Controllers.getUserId(inv);
		DesignerEntity  entity = designerService.findDesignerByUserId(sellerId);
		if(entity!=null&&StringUtils.isNotEmpty(entity.getLiveFileIds())){
			List<String> personLifeFiles =  Arrays.asList(entity.getLiveFileIds().split(","));
			inv.addModel("personLifeFiles", personLifeFiles);
		}
		return "PersonLifeEdit";
	}
	
	@Post("save")
	public Object save(Invocation inv, @Param("lifeFileIds") String lifeFileIds) throws Exception{
		UserInfo userInfo = Controllers.getUserInfo(inv);
		JsonResult json = new JsonResult();
		try{
			DesignerEntity entity = designerService.findDesignerByUserId(userInfo.getId());
			boolean bUpdate = (null != entity);
			
			if(bUpdate){
				Controllers.prepareEntityForDataSaving(entity, userInfo, bUpdate);
				entity.setLiveFileIds(lifeFileIds);
				this.designerService.updateDesigner(entity);
			} else {
				entity = new DesignerEntity();
				Controllers.prepareEntityForDataSaving(entity, userInfo, bUpdate);
				entity.setUserId(userInfo.getId());
				entity.setLiveFileIds(lifeFileIds);
				this.designerService.createDesigner(entity);
			}
			json.setSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			json.setMessage(e.getMessage());
			json.setSuccess(false);
		}
		return json;
	}
}
